package middle.ground.http.interceptor;

import middle.ground.core.annotation.Inner;
import middle.ground.core.annotation.NeedLogin;
import middle.ground.utils.RedisCacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录和鉴权验证拦截器
 *
 * @author jrl
 */
public class ApplicationRequestInterceptor extends HandlerInterceptorAdapter {

	private static final String ADMIN_TOKEN_PRE = RedisCacheUtil.SYSTEM_FLAG + "ADMIN_TOKEN_PREFIX:";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			NeedLogin needLogin = handlerMethod.getMethodAnnotation(NeedLogin.class);
			Inner inner = handlerMethod.getMethodAnnotation(Inner.class);
			if (null == needLogin || inner != null) {
				return true;
			}

			String token = request.getHeader("token");
			if (StringUtils.isBlank(token)) {
				write(response);
				return false;
			}

			Object admin = RedisCacheUtil.get(ADMIN_TOKEN_PRE + token);
			if (null == admin) {
				write(response);
				return false;
			}
		}

		return true;
	}

	private void write(HttpServletResponse response) throws IOException {
		int code = HttpServletResponse.SC_UNAUTHORIZED;
		response.setStatus(code);
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("{\"code\":" + code + ",\"status\":\"no\",\"msg\":\"无授权访问，请先登录\"}");
	}
}
